package org.book.configuration.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.book.bean.Manager;
import org.book.common.JsonResult;
import org.book.service.IManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Aspect//声明本类是切面
@Component//声明组件
@Slf4j
public class PermissionCheckAspect {
    @Autowired
    IManagerService managerService;

    @Pointcut("@annotation(org.book.configuration.aop.PermissionCheck)")//拦截被PermissionCheck注解的方法
    private void scall(){}
    /**
     * 环绕
     */
    @Around("scall()")
    public Object prepareFood(ProceedingJoinPoint joinPoint) throws Throwable{
        log.info("进入切面方法");
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();          //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        HttpSession session= request.getSession();//获取session
        String name = ""+session.getAttribute("user");//获取登录的信息
        Manager manager =null;
        try {
            manager = managerService.getById(name);
        }catch (Exception e){
            return JsonResult.renderFail("你没有权限");
        }
        if(manager==null||manager.getUsername()==null||manager.getUsername().equals("")){
            return JsonResult.renderFail("你没有权限");
        }
        return joinPoint.proceed();
    }

}
